package com.metaera.app.ui.fragments;

import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.metaera.app.Constants;
import com.metaera.app.R;
import com.metaera.app.controller.core.IPaginationPresenter;
import com.metaera.app.controller.presenter.FlashNewsListPresenter;
import com.metaera.app.controller.view.BasicPaginationView;
import com.metaera.app.controller.view.RefreshLoadMoreView;
import com.metaera.app.controller.view.core.IPaginationView;
import com.metaera.app.data.model.ArticleListResponse;
import com.metaera.app.ui.adapters.FlashNewsItemAdapter;
import com.metaera.app.ui.core.BaseRequestFragment;
import com.metaera.app.utils.DateUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import java.util.List;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 快讯
 */
public class FlashNewsItemFragment extends BaseRequestFragment {

    public static Fragment newInstance(int type) {
        Bundle bundle = new Bundle();
        bundle.putInt(Constants.CATEGORY_TYPE, type);
        FlashNewsItemFragment fragment = new FlashNewsItemFragment();
        fragment.setArguments(bundle);
        return fragment;
    }


    private TextView tv_date, tv_date_day, tv_date_week;

    @Override
    protected int getLayoutId() {
//        return R.layout.include_smart_refresh_recycler_view;
        return R.layout.fragment_flash_news_item;
    }

    @Override
    protected void initialize(Bundle savedInstanceState) {
        // find view
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        SmartRefreshLayout refreshLayout = findViewById(R.id.smart_refresh_layout);
        ViewGroup layoutDate = findViewById(R.id.layout_flash_news_date);
        tv_date = layoutDate.findViewById(R.id.tv_date);
        tv_date_day = layoutDate.findViewById(R.id.tv_date_day);
        tv_date_week = layoutDate.findViewById(R.id.tv_date_week);

        // init view
        FlashNewsItemAdapter adapter = new FlashNewsItemAdapter();
        recyclerView.setAdapter(adapter);


        // network
        if (getArguments() != null) {
            int categoryType = getArguments().getInt(Constants.CATEGORY_TYPE);
            IPaginationPresenter<IPaginationView<ArticleListResponse>, ArticleListResponse>
                    presenter = new FlashNewsListPresenter(categoryType);
            presenter.setModelAndView(new BasicPaginationView<>(recyclerView, refreshLayout, this) {
                @Override
                public void renderRefresh(List<ArticleListResponse> refreshData) {
                    super.renderRefresh(refreshData);
                    if (refreshData != null && !refreshData.isEmpty()) {
                        renderDate(refreshData.get(0));
                    }
                }
            });
            presenter.requestRefresh();

            // listener
            refreshLayout.setOnRefreshLoadMoreListener(new RefreshLoadMoreView<>(presenter));

            adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
                @Override
                public void onChanged() {
                    layoutDate.setVisibility(adapter.getData().isEmpty() ? View.GONE : View.VISIBLE);
                }

            });

            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

                int lastPosition = 0;

                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    LinearLayoutManager lm = (LinearLayoutManager) recyclerView.getLayoutManager();
                    if (lm != null) {
                        int position = lm.findFirstCompletelyVisibleItemPosition();
                        if (position >= 0 && lastPosition != position) {
                            lastPosition = position;
                            renderDate(adapter.getItem(position));
                        }
                    }
                }
            });
        }
    }

    private void renderDate(ArticleListResponse item) {
        int timestamp = item.getRelease_time_stamp();
        Resources resources = tv_date.getContext().getResources();

        tv_date.setText(DateUtils.getTime(timestamp, DateUtils.PATTERN_6));
        tv_date_day.setVisibility(DateUtils.siToday(timestamp) ? View.VISIBLE : View.GONE);
        tv_date_week.setText(DateUtils.getWeekOfTimestamp(timestamp, resources.getStringArray(R.array.weeks)));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

//    ActivityResultLauncher<String> launcher = registerForActivityResult(new ActivityResultContracts.RequestPermission(),
//            result -> {
//                if (result.equals(true)) {
//                    // 权限获取到之后的动作
//                } else {
//                    // 权限没有获取到的动作
//                }
//            });

}
